<?php

namespace app\service\home;

use app\tools\Workerman;
use Exception;
use GatewayClient\Gateway;

/**
 * 首页
 *
 * user ：Du
 * Date : 2022/3/23
 * Time : 13:45
 * Class IndexService
 * @package projects\services\home
 */
class IndexService
{

    /**
     * 在线用户统计
     *
     * User : Du
     * Date : 2022/3/23
     * Time : 14:18
     * @return bool
     * @throws Exception
     */
    public static function onlineUser(): bool
    {
        $userNumber = Gateway::getAllUidCount();  //用户数量
        $pageNumber = Gateway::getAllClientCount();  //已打开页面数量
        $data = [
            'type' => 'update_online_count',
            'page_number' => $pageNumber,
            'user_number' => $userNumber
        ];
        Workerman::sendMessage($data, 'all');
        return true;
    }

    /**
     * 绑定用户id
     *
     * User : Du
     * Date : 2022/3/23
     * Time : 17:39
     * @param array $request
     * @return bool
     * @throws Exception
     */
    public static function chatBingUser(array $request): bool
    {
        if ($_SERVER['REMOTE_ADDR'] === '127.0.0.1') {
            return true;
        }
        if (!session('user_info')) {
            $id = $_COOKIE['PHPSESSID'];
            session('client_id', $request['client_id']);
        } else {
            $id = session('user_info')['id'];
        }
        $request['id'] = $id;
        Workerman::bingUser($request);
        self::onlineUser();
        return true;
    }

    /**
     * 获取在线用户
     *
     * User : Du
     * Date : 2022/3/26
     * Time : 16:21
     * @return array
     */
    public static function getOnlineUser(): array
    {
        return Gateway::getAllUidList();
    }
}